from socket import *
from threading import Thread
import time

stop_flag = False

udpSocket = socket(AF_INET, SOCK_DGRAM)
recAddr = ('', 8760)
udpSocket.bind(recAddr)
sendAddr = ('192.168.75.111', 8765)
sendData = bytes('谚语字典查询?', encoding='utf-8')
udpSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)


def send():
    while True:
        if stop_flag:
            udpSocket.sendto(sendData, sendAddr)
            print('send success!!')
            time.sleep(0.5)
        else:
            break

def receive():
    while True:
        if stop_flag:
            recvData = udpSocket.recvfrom(1024)
            print(recvData[0].decode(encoding='utf-8', errors="strict"))
        else:
            break

if __name__ == '__main__':
    thread1 = Thread(target=send)
    thread2 = Thread(target=receive)
    while True:
        input_str = input('Please input:')
        if input_str == '1':
            stop_flag = True
            thread1.start()
            thread2.start()
        elif input_str == '0':
            stop_flag = False
            break
    udpSocket.close()
